<!DOCTYPE html>
<html lang="zh" dir="ltr" class="client-nojs">
<head>
<title>用户定义转换</title>
<meta charset="UTF-8">
<meta name="generator" content="MediaWiki 1.21.2">
<link rel="shortcut icon" href="../../../common/favicon.ico">
<link rel="stylesheet" href="../../../common/ext.css">
<meta name="ResourceLoaderDynamicStyles" content="">
<link rel="stylesheet" href="../../../common/site_modules.css">
<style>a:lang(ar),a:lang(ckb),a:lang(fa),a:lang(kk-arab),a:lang(mzn),a:lang(ps),a:lang(ur){text-decoration:none}#toc{display:none}.editsection{display:none}
/* cache key: mwiki1-mwiki_zh_:resourceloader:filter:minify-css:7:15cea3ec788a65b5187d4018eed543bf */</style>

<script src="../../../common/startup_scripts.js"></script>
<script>if(window.mw){
mw.config.set({"wgCanonicalNamespace":"","wgCanonicalSpecialPageName":false,"wgNamespaceNumber":0,"wgPageName":"cpp/language/cast_operator","wgTitle":"cpp/language/cast operator","wgCurRevisionId":64180,"wgArticleId":8562,"wgIsArticle":true,"wgAction":"view","wgUserName":null,"wgUserGroups":["*"],"wgCategories":[],"wgBreakFrames":false,"wgPageContentLanguage":"zh","wgSeparatorTransformTable":["",""],"wgDigitTransformTable":["",""],"wgDefaultDateFormat":"zh","wgMonthNames":["","1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],"wgMonthNamesShort":["","1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],"wgRelevantPageName":"cpp/language/cast_operator","wgUserVariant":"zh","wgRestrictionEdit":[],"wgRestrictionMove":[]});
}</script><script>if(window.mw){
mw.loader.implement("user.options",function(){mw.user.options.set({"ccmeonemails":0,"cols":80,"date":"default","diffonly":0,"disablemail":0,"disablesuggest":0,"editfont":"default","editondblclick":0,"editsection":0,"editsectiononrightclick":0,"enotifminoredits":0,"enotifrevealaddr":0,"enotifusertalkpages":1,"enotifwatchlistpages":0,"extendwatchlist":0,"externaldiff":0,"externaleditor":0,"fancysig":0,"forceeditsummary":0,"gender":"unknown","hideminor":0,"hidepatrolled":0,"imagesize":2,"justify":0,"math":1,"minordefault":0,"newpageshidepatrolled":0,"nocache":0,"noconvertlink":0,"norollbackdiff":0,"numberheadings":0,"previewonfirst":0,"previewontop":1,"quickbar":5,"rcdays":7,"rclimit":50,"rememberpassword":0,"rows":25,"searchlimit":20,"showhiddencats":0,"showjumplinks":1,"shownumberswatching":1,"showtoc":0,"showtoolbar":1,"skin":"cppreference2","stubthreshold":0,"thumbsize":2,"underline":2,"uselivepreview":0,"usenewrc":0,"watchcreations":0,"watchdefault":0,"watchdeletion":0,
"watchlistdays":3,"watchlisthideanons":0,"watchlisthidebots":0,"watchlisthideliu":0,"watchlisthideminor":0,"watchlisthideown":0,"watchlisthidepatrolled":0,"watchmoves":0,"wllimit":250,"variant":"zh","language":"zh","searchNs0":true,"searchNs1":false,"searchNs2":false,"searchNs3":false,"searchNs4":false,"searchNs5":false,"searchNs6":false,"searchNs7":false,"searchNs8":false,"searchNs9":false,"searchNs10":false,"searchNs11":false,"searchNs12":false,"searchNs13":false,"searchNs14":false,"searchNs15":false,"gadget-MathJax":1,"gadget-ColiruCompiler":1});;},{},{});mw.loader.implement("user.tokens",function(){mw.user.tokens.set({"editToken":"+\\","patrolToken":false,"watchToken":false});;},{},{});
/* cache key: mwiki1-mwiki_zh_:resourceloader:filter:minify-js:7:258d7cd6aa9aa67dee25e01fb6a9e505 */
}</script>
<script>if(window.mw){
mw.loader.load(["mediawiki.page.startup","mediawiki.legacy.wikibits","mediawiki.legacy.ajax"]);
}</script>
<style type="text/css">/*<![CDATA[*/
.source-cpp {line-height: normal;}
.source-cpp li, .source-cpp pre {
	line-height: normal; border: 0px none white;
}
/**
 * GeSHi Dynamically Generated Stylesheet
 * --------------------------------------
 * Dynamically generated stylesheet for cpp
 * CSS class: source-cpp, CSS id: 
 * GeSHi (C) 2004 - 2007 Nigel McNie, 2007 - 2008 Benny Baumann
 * (http://qbnz.com/highlighter/ and http://geshi.org/)
 * --------------------------------------
 */
.cpp.source-cpp .de1, .cpp.source-cpp .de2 {font: normal normal 1em/1.2em monospace; margin:0; padding:0; background:none; vertical-align:top;}
.cpp.source-cpp  {font-family:monospace;}
.cpp.source-cpp .imp {font-weight: bold; color: red;}
.cpp.source-cpp li, .cpp.source-cpp .li1 {font-weight: normal; vertical-align:top;}
.cpp.source-cpp .ln {width:1px;text-align:right;margin:0;padding:0 2px;vertical-align:top;}
.cpp.source-cpp .li2 {font-weight: bold; vertical-align:top;}
.cpp.source-cpp .kw1 {color: #0000dd;}
.cpp.source-cpp .kw2 {color: #0000ff;}
.cpp.source-cpp .kw3 {color: #0000dd;}
.cpp.source-cpp .kw4 {color: #0000ff;}
.cpp.source-cpp .co1 {color: #909090;}
.cpp.source-cpp .co2 {color: #339900;}
.cpp.source-cpp .coMULTI {color: #ff0000; font-style: italic;}
.cpp.source-cpp .es0 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es1 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es2 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es3 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es4 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es5 {color: #008000; font-weight: bold;}
.cpp.source-cpp .br0 {color: #008000;}
.cpp.source-cpp .sy0 {color: #008000;}
.cpp.source-cpp .sy1 {color: #000080;}
.cpp.source-cpp .sy2 {color: #000040;}
.cpp.source-cpp .sy3 {color: #000040;}
.cpp.source-cpp .sy4 {color: #008080;}
.cpp.source-cpp .st0 {color: #008000;}
.cpp.source-cpp .nu0 {color: #000080;}
.cpp.source-cpp .nu6 {color: #000080;}
.cpp.source-cpp .nu8 {color: #000080;}
.cpp.source-cpp .nu12 {color: #000080;}
.cpp.source-cpp .nu16 {color:#000080;}
.cpp.source-cpp .nu17 {color:#000080;}
.cpp.source-cpp .nu18 {color:#000080;}
.cpp.source-cpp .nu19 {color:#000080;}
.cpp.source-cpp .ln-xtra, .cpp.source-cpp li.ln-xtra, .cpp.source-cpp div.ln-xtra {background-color: #ffc;}
.cpp.source-cpp span.xtra { display:block; }

/*]]>*/
</style><!--[if lt IE 7]><style type="text/css">body{behavior:url("/mwiki/skins/cppreference2/csshover.min.htc")}</style><![endif]--></head>
<body class="mediawiki ltr sitedir-ltr ns-0 ns-subject page-cpp_language_cast_operator skin-cppreference2 action-view cpp-navbar">
        <!-- header -->
        <!-- /header -->
        <!-- content -->
<div id="cpp-content-base">
            <div id="content">
                <a id="top"></a>
                <div id="mw-js-message" style="display:none;"></div>
                                <!-- firstHeading -->
<h1 id="firstHeading" class="firstHeading">用户定义转换</h1>
                <!-- /firstHeading -->
                <!-- bodyContent -->
                <div id="bodyContent">
                                        <!-- tagline -->
                    <div id="siteSub">来自cppreference.com</div>
                    <!-- /tagline -->
                                        <!-- subtitle -->
                    <div id="contentSub"><span class="subpages">&lt; <a href="../../cpp.html" title="cpp">cpp</a>‎ | <a href="../language.html" title="cpp/language">language</a></span></div>
                    <!-- /subtitle -->
                                                            <!-- bodycontent -->
                    <div id="mw-content-text" lang="zh" dir="ltr" class="mw-content-ltr"><div class="t-navbar" style=""><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="../../cpp.html" title="cpp"> C++</a><div class="t-navbar-menu"><div><div><table class="t-nv-begin" cellpadding="0" style="line-height:1.1em;">
<tr class="t-nv"><td colspan="5"> <a href="../language.html" title="cpp/language">语言</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../header.html" title="cpp/header">标准库头文件</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../freestanding.html" title="cpp/freestanding"> 自立与有宿主实现</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../named_req.html" title="cpp/named req">具名要求</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../utility.html#.E8.AF.AD.E8.A8.80.E6.94.AF.E6.8C.81" title="cpp/utility">语言支持库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../concepts.html" title="cpp/concepts">概念库</a> <span class="t-mark-rev t-since-cxx20">(C++20)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../error.html" title="cpp/error">诊断库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../utility.html" title="cpp/utility">工具库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../string.html" title="cpp/string">字符串库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="https://zh.cppreference.com/w/cpp/container" title="cpp/container">容器库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../iterator.html" title="cpp/iterator">迭代器库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../ranges.html" title="cpp/ranges"> 范围库</a> <span class="t-mark-rev t-since-cxx20">(C++20)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../algorithm.html" title="cpp/algorithm">算法库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../numeric.html" title="cpp/numeric">数值库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../io.html" title="cpp/io">输入/输出库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../locale.html" title="cpp/locale">本地化库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../regex.html" title="cpp/regex">正则表达式库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../atomic.html" title="cpp/atomic">原子操作库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../thread.html" title="cpp/thread">线程支持库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../filesystem.html" title="cpp/filesystem">文件系统库</a> <span class="t-mark-rev t-since-cxx17">(C++17)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../experimental.html" title="cpp/experimental">技术规范</a> </td></tr>
</table></div><div></div></div></div></div><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="../language.html" title="cpp/language">C++ 语言</a></div><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="expressions.html" title="cpp/language/expressions"> 表达式</a><div class="t-navbar-menu"><div><div style="display:inline-block">
<div><table class="t-nv-begin" cellpadding="0" style="">
<tr class="t-nv-h2"><td colspan="5"> 概述 </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="value_category.html" title="cpp/language/value category"> 值类别</a>（左值 lvalue、右值 rvalue、亡值 xvalue）</td></tr>
<tr class="t-nv"><td colspan="5"> <a href="eval_order.html" title="cpp/language/eval order"> 求值顺序</a>（序列点）</td></tr>
<tr class="t-nv"><td colspan="5"> <a href="constant_expression.html" title="cpp/language/constant expression"> 常量表达式</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="expressions.html#.E4.B8.8D.E6.B1.82.E5.80.BC.E8.A1.A8.E8.BE.BE.E5.BC.8F" title="cpp/language/expressions"> 不求值表达式</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="expressions.html#.E5.88.9D.E7.AD.89.E8.A1.A8.E8.BE.BE.E5.BC.8F" title="cpp/language/expressions"> 初等表达式</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="lambda.html" title="cpp/language/lambda">lambda 表达式</a><span class="t-mark-rev t-since-cxx11">(C++11)</span></td></tr>
<tr class="t-nv-h2"><td colspan="5"> 字面量 </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="integer_literal.html" title="cpp/language/integer literal">整数字面量</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="floating_literal.html" title="cpp/language/floating literal">浮点字面量</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="bool_literal.html" title="cpp/language/bool literal">布尔字面量</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="character_literal.html" title="cpp/language/character literal">字符字面量</a>，包含<a href="escape.html" title="cpp/language/escape">转义序列</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="string_literal.html" title="cpp/language/string literal">字符串字面量</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="nullptr.html" title="cpp/language/nullptr">空指针字面量</a><span class="t-mark-rev t-since-cxx11">(C++11)</span></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="user_literal.html" title="cpp/language/user literal">用户定义字面量</a><span class="t-mark-rev t-since-cxx11">(C++11)</span></td></tr>
<tr class="t-nv-h2"><td colspan="5"> 运算符 </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="operator_assignment.html" title="cpp/language/operator assignment"> 赋值运算符</a>:
<code>a=b</code>, <code>a+=b</code>, <code>a-=b</code>, <code>a*=b</code>, <code>a/=b</code>, <code>a%=b</code>, <code>a&amp;=b</code>, <code>a|=b</code>, <code>a^=b</code>, <code>a&lt;&lt;=b</code>, <code>a&gt;&gt;=b</code></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="operator_incdec.html" title="cpp/language/operator incdec"> 自增与自减</a>: <code>++a</code>, <code>--a</code>, <code>a++</code>, <code>a--</code></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="operator_arithmetic.html" title="cpp/language/operator arithmetic"> 算术运算符</a>:
<code>+a</code>, <code>-a</code>, <code>a+b</code>, <code>a-b</code>, <code>a*b</code>, <code>a/b</code>, <code>a%b</code>, <code>~a</code>, <code>a&amp;b</code>, <code>a|b</code>, <code>a^b</code>, <code>a&lt;&lt;b</code>, <code>a&gt;&gt;b</code> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="operator_logical.html" title="cpp/language/operator logical"> 逻辑运算符</a>: <code>a||b</code>, <code>a&amp;&amp;b</code>, <code>!a</code></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="operator_comparison.html" title="cpp/language/operator comparison"> 比较运算符</a>: <code>a==b</code>, <code>a!=b</code>, <code>a&lt;b</code>, <code>a&gt;b</code>, <code>a&lt;=b</code>, <code>a&gt;=b</code>, <code>a&lt;=&gt;b</code><span class="t-mark-rev t-since-cxx20">(C++20)</span></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="operator_member_access.html" title="cpp/language/operator member access"> 成员访问运算符</a>: <code>a[b]</code>, <code>*a</code>, <code>&amp;a</code>, <code>a-&gt;b</code>, <code>a.b</code>, <code>a-&gt;*b</code>, <code>a.*b</code></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="operator_other.html" title="cpp/language/operator other"> 其他运算符</a>: <code>a(...)</code>, <code>a,b</code>, <code>a?b:c</code> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="default_comparisons.html" title="cpp/language/default comparisons">默认比较</a><span class="t-mark-rev t-since-cxx20">(C++20)</span></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="operator_alternative.html" title="cpp/language/operator alternative">运算符的代用表示</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="operator_precedence.html" title="cpp/language/operator precedence">优先级和结合性</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="fold.html" title="cpp/language/fold">折叠表达式</a><span class="t-mark-rev t-since-cxx17">(C++17)</span></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="new.html" title="cpp/language/new">new 表达式</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="delete.html" title="cpp/language/delete">delete 表达式</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="throw.html" title="cpp/language/throw">throw 表达式</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="alignof.html" title="cpp/language/alignof">alignof</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="sizeof.html" title="cpp/language/sizeof">sizeof</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="sizeof....html" title="cpp/language/sizeof...">sizeof...</a><span class="t-mark-rev t-since-cxx11">(C++11)</span></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="typeid.html" title="cpp/language/typeid">typeid</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="noexcept.html" title="cpp/language/noexcept">noexcept</a><span class="t-mark-rev t-since-cxx11">(C++11)</span></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="operators.html" title="cpp/language/operators">运算符重载</a></td></tr>
<tr class="t-nv-h2"><td colspan="5"> 类型转换 </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="implicit_cast.html" title="cpp/language/implicit conversion">隐式转换</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="const_cast.html" title="cpp/language/const cast">const_cast</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="static_cast.html" title="cpp/language/static cast">static_cast</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="reinterpret_cast.html" title="cpp/language/reinterpret cast">reinterpret_cast</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="dynamic_cast.html" title="cpp/language/dynamic cast">dynamic_cast</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="explicit_cast.html" title="cpp/language/explicit cast">显式转换</a> <code>(T)a</code>, <code>T(a)</code></td></tr>
<tr class="t-nv"><td colspan="5"> <strong class="selflink">用户定义转换</strong></td></tr>
</table></div>
</div><div></div></div></div></div><div class="t-navbar-sep"> </div></div>
<p>允许从<a href="class.html" title="cpp/language/class">类类型</a>到其他类型的<a href="implicit_cast.html" title="cpp/language/implicit conversion">隐式转换</a>或<a href="explicit_cast.html" title="cpp/language/explicit cast">显式转换</a>。
</p>
<h3><span class="mw-headline" id=".E8.AF.AD.E6.B3.95">语法</span></h3>
<p>转换函数的声明类似于<a href="member_functions.html" title="cpp/language/member functions">非静态成员函数</a>或<a href="function_template.html" title="cpp/language/function template">函数模板</a>，但没有参数或显式返回类型，并拥有下列形式的名字：
</p>
<table class="t-sdsc-begin">

<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr>
<tr class="t-sdsc">
<td> <code><b>operator</b></code> <span class="t-spar">转换类型标识</span>
</td>
<td> (1)
</td>
<td class="t-sdsc-nopad">
</td></tr>



<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr>
<tr class="t-sdsc">
<td> <code><b>explicit</b></code> <code><b>operator</b></code> <span class="t-spar">转换类型标识</span>
</td>
<td> (2)
</td>
<td> <span class="t-mark-rev t-since-cxx11">(C++11 起)</span>
</td></tr>



<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr>
<tr class="t-sdsc">
<td> <code><b>explicit (</b></code> <span class="t-spar">表达式</span> <code><b>)</b></code> <code><b>operator</b></code> <span class="t-spar">转换类型标识</span>
</td>
<td> (3)
</td>
<td> <span class="t-mark-rev t-since-cxx20">(C++20 起)</span>
</td></tr>



<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr></table>
<div class="t-li1"><span class="t-li">1)</span> 声明用户定义的转换函数，它参与所有<a href="implicit_cast.html" title="cpp/language/implicit conversion">隐式</a>和<a href="explicit_cast.html" title="cpp/language/explicit cast">显式</a>转换。</div>
<div class="t-li1"><span class="t-li">2)</span> 声明用户定义的转换函数，它仅参与<a href="direct_initialization.html" title="cpp/language/direct initialization">直接初始化</a>和<a href="explicit_cast.html" title="cpp/language/explicit cast">显式转换</a>。</div>
<div class="t-li1"><span class="t-li">3)</span> 声明用户定义的转换函数，它为<a href="explicit.html" title="cpp/language/explicit">条件性 explicit</a> 。</div>
<p><span class="t-spar">转换类型标识</span>是一个<a href="incomplete_type.html#.E7.B1.BB.E5.9E.8B.E7.9A.84.E5.91.BD.E5.90.8D" title="cpp/language/type">类型标识</a>，但其声明器中不允许出现函数与数组运算符 <code><b>[]</b></code> 或 <code><b>()</b></code>（因此，转换到诸如数组的指针的类型要求使用类型别名、typedef 或标识模板：见下文）。无论是否使用 typedef，<span class="t-spar">转换类型标识</span>都不能代表数组或函数类型。
</p><p>尽管用户定义转换函数的声明中不允许出现返回类型，<a href="declarations.html#.E8.AF.B4.E6.98.8E.E7.AC.A6" title="cpp/language/declarations">声明的文法</a>中的 <span class="t-spar">声明说明符序列</span>可以存在并可包含除了 <span class="t-spar">类型说明符</span> 或关键词 <code>static</code> 之外的任何说明符。尤其是，其不仅允许 <code>explicit</code>，亦允许说明符 <a href="inline.html" title="cpp/language/inline"><code>inline</code></a>、<a href="virtual.html" title="cpp/language/virtual"><code>virtual</code></a><span class="t-rev-inl t-since-cxx11"><span>、<a href="constexpr.html" title="cpp/language/constexpr"><code>constexpr</code></a></span> <span><span class="t-mark-rev t-since-cxx11">(C++11 起)</span></span></span><span class="t-rev-inl t-since-cxx20"><span>、<a href="consteval.html" title="cpp/language/consteval"><code>consteval</code></a></span> <span><span class="t-mark-rev t-since-cxx20">(C++20 起)</span></span></span> 及 <a href="friend.html" title="cpp/language/friend"><code>friend</code></a>（注意 <code>friend</code> 要求有限定名：<code>friend A::operator B();</code>）。
</p><p>如果在类 X 中声明这种成员函数，则它进行从 X 到 <span class="t-spar">转换类型标识</span> 的转换：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw1">struct</span> X <span class="br0">{</span>
    <span class="co1">// 隐式转换</span>
    operator <span class="kw4">int</span><span class="br0">(</span><span class="br0">)</span> <span class="kw4">const</span> <span class="br0">{</span> <span class="kw1">return</span> <span class="nu0">7</span><span class="sy4">;</span> <span class="br0">}</span>
 
    <span class="co1">// 显式转换</span>
    <span class="kw1">explicit</span> operator <span class="kw4">int</span><span class="sy2">*</span><span class="br0">(</span><span class="br0">)</span> <span class="kw4">const</span> <span class="br0">{</span> <span class="kw1">return</span> nullptr<span class="sy4">;</span> <span class="br0">}</span>
 
<span class="co1">//   错误：转换类型标识中不允许出现数组运算符</span>
<span class="co1">//   operator int(*)[3]() const { return nullptr; }</span>
    <span class="kw1">using</span> arr_t <span class="sy1">=</span> <span class="kw4">int</span><span class="br0">[</span><span class="nu0">3</span><span class="br0">]</span><span class="sy4">;</span>
    operator arr_t<span class="sy2">*</span><span class="br0">(</span><span class="br0">)</span> <span class="kw4">const</span> <span class="br0">{</span> <span class="kw1">return</span> nullptr<span class="sy4">;</span> <span class="br0">}</span> <span class="co1">// 若通过 typedef 进行则 OK</span>
<span class="co1">//  operator arr_t () const; // 错误：不允许任何情况下转换到数组</span>
<span class="br0">}</span><span class="sy4">;</span>
 
<span class="kw4">int</span> main<span class="br0">(</span><span class="br0">)</span>
<span class="br0">{</span>
    X x<span class="sy4">;</span>
 
    <span class="kw4">int</span> n <span class="sy1">=</span> <span class="kw1">static_cast</span><span class="sy1">&lt;</span><span class="kw4">int</span><span class="sy1">&gt;</span><span class="br0">(</span>x<span class="br0">)</span><span class="sy4">;</span>   <span class="co1">// OK：设 n 为 7</span>
    <span class="kw4">int</span> m <span class="sy1">=</span> x<span class="sy4">;</span>                     <span class="co1">// OK：设 m 为 7</span>
 
    <span class="kw4">int</span><span class="sy2">*</span> p <span class="sy1">=</span> <span class="kw1">static_cast</span><span class="sy1">&lt;</span><span class="kw4">int</span><span class="sy2">*</span><span class="sy1">&gt;</span><span class="br0">(</span>x<span class="br0">)</span><span class="sy4">;</span>  <span class="co1">// OK：设 p 为 null</span>
<span class="co1">//  int* q = x; // 错误：无隐式转换</span>
 
    <span class="kw4">int</span> <span class="br0">(</span><span class="sy2">*</span>pa<span class="br0">)</span><span class="br0">[</span><span class="nu0">3</span><span class="br0">]</span> <span class="sy1">=</span> x<span class="sy4">;</span>  <span class="co1">// OK</span>
<span class="br0">}</span></pre></div></div>
<h3><span class="mw-headline" id=".E8.A7.A3.E9.87.8A">解释</span></h3>
<p>用户定义的转换函数在<a href="implicit_cast.html" title="cpp/language/implicit conversion">隐式转换</a>的第二阶段被调用，第二阶段由零或一个<a href="converting_constructor.html" title="cpp/language/converting constructor">转换构造函数</a>或零或一个用户定义转换函数构成。
</p><p>若转换函数和转换构造函数都能用于进行某个用户定义转换，则<a href="copy_initialization.html" title="cpp/language/copy initialization">复制初始化</a>和<a href="reference_initialization.html" title="cpp/language/reference initialization">引用初始化</a>语境中的<a href="overload_resolution.html" title="cpp/language/overload resolution">重载决议</a>同时考虑转换函数和转换构造函数，但在<a href="direct_initialization.html" title="cpp/language/direct initialization">直接初始化</a>语境中只考虑转换构造函数。
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw1">struct</span> To <span class="br0">{</span>
    To<span class="br0">(</span><span class="br0">)</span> <span class="sy1">=</span> <span class="kw1">default</span><span class="sy4">;</span>
    To<span class="br0">(</span><span class="kw4">const</span> <span class="kw1">struct</span> From<span class="sy3">&amp;</span><span class="br0">)</span> <span class="br0">{</span><span class="br0">}</span> <span class="co1">// 转换构造函数</span>
<span class="br0">}</span><span class="sy4">;</span>
 
<span class="kw1">struct</span> From <span class="br0">{</span>
    operator To<span class="br0">(</span><span class="br0">)</span> <span class="kw4">const</span> <span class="br0">{</span><span class="kw1">return</span> To<span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span><span class="br0">}</span> <span class="co1">// 转换函数</span>
<span class="br0">}</span><span class="sy4">;</span>
 
<span class="kw4">int</span> main<span class="br0">(</span><span class="br0">)</span>
<span class="br0">{</span>
    From f<span class="sy4">;</span>
    To t1<span class="br0">(</span>f<span class="br0">)</span><span class="sy4">;</span> <span class="co1">// 直接初始化：调用构造函数</span>
<span class="co1">// （注意，若转换构造函数不可用，则选择隐式复制构造函数，且调用转换函数以准备其参数）</span>
    To t2 <span class="sy1">=</span> f<span class="sy4">;</span> <span class="co1">// 复制初始化：歧义</span>
<span class="co1">// （注意，若转换函数来自非 const 类型，例如 From::operator To(); </span>
<span class="co1">//  则它在此情况中替代构造函数被选中）</span>
    To t3 <span class="sy1">=</span> <span class="kw1">static_cast</span><span class="sy1">&lt;</span>To<span class="sy1">&gt;</span><span class="br0">(</span>f<span class="br0">)</span><span class="sy4">;</span> <span class="co1">// 直接初始化：调用构造函数</span>
    <span class="kw4">const</span> To<span class="sy3">&amp;</span> r <span class="sy1">=</span> f<span class="sy4">;</span> <span class="co1">// 引用初始化：歧义</span>
<span class="br0">}</span></pre></div></div>
<p>可以定义转换到其自身（可有 cv 限定）类（或其引用），转换到其自身类的基类（或其引用），和转换到类型 <span class="t-c"><span class="mw-geshi cpp source-cpp"><span class="kw4">void</span></span></span> 的转换函数，但它无法作为转换序列的一部分执行，除非在某些情况下通过<a href="virtual.html" title="cpp/language/virtual">虚</a>派发来执行：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw1">struct</span> D<span class="sy4">;</span>
<span class="kw1">struct</span> B <span class="br0">{</span>
    <span class="kw1">virtual</span> operator D<span class="br0">(</span><span class="br0">)</span> <span class="sy1">=</span> <span class="nu0">0</span><span class="sy4">;</span>
<span class="br0">}</span><span class="sy4">;</span>
<span class="kw1">struct</span> D <span class="sy4">:</span> B
<span class="br0">{</span>
    operator D<span class="br0">(</span><span class="br0">)</span> override <span class="br0">{</span> <span class="kw1">return</span> D<span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span> <span class="br0">}</span>
<span class="br0">}</span><span class="sy4">;</span>
 
<span class="kw4">int</span> main<span class="br0">(</span><span class="br0">)</span>
<span class="br0">{</span>
    D obj<span class="sy4">;</span>
    D obj2 <span class="sy1">=</span> obj<span class="sy4">;</span> <span class="co1">// 不调用 D::operator D()</span>
    B<span class="sy3">&amp;</span> br <span class="sy1">=</span> obj<span class="sy4">;</span>
    D obj3 <span class="sy1">=</span> br<span class="sy4">;</span> <span class="co1">// 通过虚派发调用 D::operator D() </span>
<span class="br0">}</span></pre></div></div>
<p>它亦可用成员函数调用语法调用：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw1">struct</span> B <span class="br0">{</span><span class="br0">}</span><span class="sy4">;</span>
<span class="kw1">struct</span> X <span class="sy4">:</span> B <span class="br0">{</span>
    operator B<span class="sy3">&amp;</span><span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span> <span class="kw1">return</span> <span class="sy2">*</span>this<span class="sy4">;</span> <span class="br0">}</span><span class="sy4">;</span>
<span class="br0">}</span><span class="sy4">;</span>
 
<span class="kw4">int</span> main<span class="br0">(</span><span class="br0">)</span>
<span class="br0">{</span>
    X x<span class="sy4">;</span>
    B<span class="sy3">&amp;</span> b1 <span class="sy1">=</span> x<span class="sy4">;</span>                  <span class="co1">// 不调用 X::operatorB&amp;()</span>
    B<span class="sy3">&amp;</span> b2 <span class="sy1">=</span> <span class="kw1">static_cast</span><span class="sy1">&lt;</span>B<span class="sy3">&amp;</span><span class="sy1">&gt;</span><span class="br0">(</span>x<span class="br0">)</span><span class="sy4">;</span> <span class="co1">// 不调用 X::operatorB&amp;</span>
    B<span class="sy3">&amp;</span> b3 <span class="sy1">=</span> x.<span class="me1">operator</span> B<span class="sy3">&amp;</span><span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span>    <span class="co1">// 调用 X::operatorB&amp;</span>
<span class="br0">}</span></pre></div></div>
<p>显式调用转换函数时，<span class="t-spar">类型标识</span> 是贪心的：它是可作为合法 <span class="t-spar">类型标识</span> 的最长可能的记号序列（包括属性，若存在）：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="sy3">&amp;</span> x.<span class="me1">operator</span> <span class="kw4">int</span> <span class="sy2">*</span> a<span class="sy4">;</span> <span class="co1">// 分析为 &amp; (x.operator int*) a</span>
                      <span class="co1">// 而非 &amp; (x.operator int) * a</span></pre></div></div>
 <table class="t-rev-begin">
<tr class="t-rev t-since-cxx14"><td>
<p><span class="t-spar">转换类型标识</span> 中可以使用占位符 <a href="auto.html" title="cpp/language/auto">auto</a>，以指定一个<a href="function.html#.E8.BF.94.E5.9B.9E.E7.B1.BB.E5.9E.8B.E6.8E.A8.E5.AF.BC" title="cpp/language/function">推导的返回类型</a>：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw1">struct</span> X <span class="br0">{</span>
    operator <span class="kw4">int</span><span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span> <span class="co1">// OK</span>
    operator <span class="kw4">auto</span><span class="br0">(</span><span class="br0">)</span> <span class="sy2">-</span><span class="sy1">&gt;</span> <span class="kw4">short</span><span class="sy4">;</span>  <span class="co1">// 错误：尾随返回类型不是语法的一部分</span>
    operator <span class="kw4">auto</span><span class="br0">(</span><span class="br0">)</span> <span class="kw4">const</span> <span class="br0">{</span> <span class="kw1">return</span> <span class="nu0">10</span><span class="sy4">;</span> <span class="br0">}</span> <span class="co1">// OK：推导的返回类型</span>
<span class="br0">}</span><span class="sy4">;</span></pre></div></div> 
<p>注意：<a href="member_template.html#.E8.BD.AC.E6.8D.A2.E5.87.BD.E6.95.B0.E6.A8.A1.E6.9D.BF" title="cpp/language/member template">转换函数模板</a>不允许具有推导的返回类型。
</p>
</td>
<td><span class="t-mark-rev t-since-cxx14">(C++14 起)</span></td></tr>
</table>
<p>转换函数可以继承而且可以为<a href="virtual.html" title="cpp/language/virtual">虚函数</a>，但不能为<a href="static.html" title="cpp/language/static">静态函数</a>。派生类中的转换函数不会隐藏基类中的转换函数，除非它们转换到同一类型。
</p><p>转换函数可以为模板成员函数，例如 <a href="../memory/auto_ptr/operator_auto_ptr.html" title="cpp/memory/auto ptr/operator auto ptr">std::auto_ptr&lt;T&gt;::operator auto_ptr&lt;Y&gt;</a>。其适用的特殊规则参阅<a href="member_template.html#.E8.BD.AC.E6.8D.A2.E5.87.BD.E6.95.B0.E6.A8.A1.E6.9D.BF" title="cpp/language/member template">成员模板</a>和<a href="template_argument_deduction.html#.E8.BD.AC.E6.8D.A2.E5.87.BD.E6.95.B0.E6.A8.A1.E6.9D.BF" title="cpp/language/template argument deduction">模板实参推导</a>。
</p>
<!-- 
NewPP limit report
Preprocessor visited node count: 2046/1000000
Preprocessor generated node count: 5545/1000000
Post‐expand include size: 60924/2097152 bytes
Template argument size: 11703/2097152 bytes
Highest expansion depth: 13/40
Expensive parser function count: 0/100
-->

<!-- Saved in parser cache with key mwiki1-mwiki_zh_:pcache:idhash:8562-0!*!0!!*!*!zh!* and timestamp 20200128182712 -->
</div>                    <!-- /bodycontent -->
                                        <!-- printfooter -->
                    <div class="printfooter">
                    来自“<a href="https://zh.cppreference.com/mwiki/index.php?title=cpp/language/cast_operator&amp;oldid=64180">https://zh.cppreference.com/mwiki/index.php?title=cpp/language/cast_operator&amp;oldid=64180</a>”                    </div>
                    <!-- /printfooter -->
                                                            <!-- catlinks -->
                    <!-- /catlinks -->
                                                            <div class="visualClear"></div>
                    <!-- debughtml -->
                                        <!-- /debughtml -->
                </div>
                <!-- /bodyContent -->
            </div>
        </div>
        <!-- /content -->
        <!-- footer -->
        <div id="cpp-footer-base" class="noprint">
            <div id="footer">
                        <div id="cpp-navigation">
            <h5>导航</h5>
            <ul><li><a href="https://zh.cppreference.com/w/cpp/language/cast_operator">Online version</a></li><li>Offline version retrieved 2020-03-14 18:00.</li></ul></div>
                        <ul id="footer-info">
                                    <li id="footer-info-lastmod"> 本页面最后修改于2020年1月28日 (星期二) 10:27。</li>
                                    <li id="footer-info-viewcount">此页面已被浏览过5,244次。</li>
                            </ul>
                    </div>
        </div>
        <!-- /footer -->
        <script>if(window.mw){
mw.loader.state({"site":"loading","user":"missing","user.groups":"ready"});
}</script>
<script src="../../../common/skin_scripts.js"></script>
<script>if(window.mw){
mw.loader.load(["mediawiki.action.view.postEdit","mediawiki.user","mediawiki.page.ready","mediawiki.searchSuggest","mediawiki.hidpi","ext.gadget.MathJax","ext.gadget.ColiruCompiler"], null, true);
}</script>
<script src="../../../common/site_scripts.js"></script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-2828341-1']);
_gaq.push(['_setDomainName', 'cppreference.com']);
_gaq.push(['_trackPageview']);
</script><!-- Served in 0.062 secs. -->
	</body>
<!-- Cached 20200128201940 -->
</html>